package com.sso.shiro;

import com.alibaba.fastjson.JSONObject;
import com.sso.common.ConstantDate;
import com.tools.util.DESUtils;
import com.tools.util.JSONUtils;
import com.tools.util.RequestUtils;
import com.tools.util.StrUtils;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口专用拦截器，专门拦截接口类型的请求
 * 处理接口访问状态及机构访问标识
 */
public class WebServiceAuthorizationFilter extends MyPermsAuthorizationFilter{
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        String urlStatus = this.isUrlAccessStatus(httpRequest);
        if(StrUtils.isNotEmpty(urlStatus)){
            JSONUtils.outputJson(ConstantDate.InterfaceStatus.SYS_ACCESS_ERROR,urlStatus,httpResponse);
            return false;
        }
        return isAccessAllowed(request,response,mappedValue) || onAccessDenied(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response,Object mappedValue) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse=WebUtils.toHttp(response);
        DESUtils des = new DESUtils("service");
        //获取加密的机构标识
        String sysEname = RequestUtils.getParameters(httpRequest,"sysEname");
        //解密
        sysEname = des.decrypt(sysEname);
        //判断访问服务器是否带入sysEname标识
        if(StrUtils.isEmpty(sysEname)){
            JSONUtils.outputJson(ConstantDate.InterfaceStatus.SYS_ACCESS_ERROR,"请勿非法访问",httpResponse);
            return false;
        }
        httpRequest.getSession().setAttribute("sysEname",sysEname);
        return true;
//        //判断该接口是否需要登陆校验
//        if(!isAccessAllowed(request,response,mappedValue)){
//            return true;
//        }
//        //判断用户是否登陆
//        if(subject.isAuthenticated()){
//            json.put("status", ConstantDate.InterfaceMessageStatus.RETURN_ERROR);
//            json.put("info","您未登陆或已登陆超时请重新登陆");
//            httpResponse.getWriter().print(json.toJSONString());
//            return false;
//        }else{
//            return true;
//        }
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
//        String[] perms = (String[]) mappedValue;
//        boolean isPermitted = false;
//        if (perms != null && perms.length > 0) {
//            //判断该接口是否需要登陆
//            if ("login".equals(perms[0])) {
//                isPermitted = true;
//            }
//        }
//        return isPermitted;
        return false;
    }
}
